package com.engine.workflow.xinri.web;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.mobile.sso.util.TokenStore;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.workflow.webservices.WorkflowServiceImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author dusongsong
 * @date 2023年05月12日 14:20
 */
public class WfUtil extends BaseBean {

    /**
     * 获取workflowID
     */
    public String getWorkflowId(String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select workflowid from workflow_requestbase where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 提交流程
     */
    public String submitWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.submitWorkflowRequest(null, requestid, userid, "submit", "由外部调用提交完成");
    }

    /**
     * 获取表单ID
     */
    public String getFormid(String workflowid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select abs(formid) from workflow_base where id=?", workflowid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 更新主表表单信息
     */
    public boolean updateMainData(String tablename, String requestid, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
        //遍历数据 进行update
        String updatesql = "update " + tablename + " set ";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            updatesql += key + "='" + map.get(key).toString() + "',";
        }
        if (updatesql.endsWith(",")) {
            updatesql = updatesql.substring(0, updatesql.length() - 1);
            updatesql += " where requestid=" + requestid;
        }
        writeLog(">>>>>updateMainData>>>>updatesql=" + updatesql);
        return rs.executeUpdate(updatesql);
    }

    /**
     * 更新明细表单信息
     */
    public boolean updateDetailData(String tablename, Map<String, Object> map) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (map.get(key) == null || "".equals(map.get(key).toString())) {
                continue;
            }
            keyString += key + ",";
            valueString += "'" + map.get(key).toString() + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        writeLog(">>>>>updateDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 删除明细表数据
     */
    public boolean deleteDetailData(String tableName, String mainid) {
        RecordSet rs = new RecordSet();
        return rs.executeUpdate("delete from  " + tableName + " where mainid=?", mainid);
    }

    /**
     * 获取明细主键ID
     */
    public String getIdByRequestId(String tableName, String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from " + tableName + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 私钥解密
     * @param encryptStr
     * @return
     */
    public String getDecryptStr(String encryptStr) {
        RecordSet rs = new RecordSet();
        //String appid = "EEAA5436-7577-4BE0-8C6C-89E9D888";
        String appid = "weaver";
        String decryptStr = "";
        try {
            rs.executeQuery("select RSA_PRV from ECOLOGY_BIZ_EC where appid=?", appid);
            rs.next();
            String prv = Util.null2String(rs.getString(1));
            writeLog("prv=" + prv);
            RSA rsa = new RSA(prv, null);
            decryptStr = rsa.decryptStr(encryptStr, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptStr;
    }

    /**
     * 校验token
     *
     * @param encrypttoken
     * @return
     */
    public Map<String, Object> checkToken(String encrypttoken) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String token = Util.null2String(getDecryptStr(encrypttoken));
        TokenStore tokenStore = new TokenStore();
        boolean hasToken = tokenStore.exists(token, 1);
        if (hasToken) {
            apidatas.put("code", "SUCCESS");
        } else {
            apidatas.put("code", "HEAD_PARAM_ERROR");
            JSONObject dataJson = new JSONObject();
            dataJson.put("token", "token不存在或者超时:" + token);
            apidatas.put("data", dataJson);
            apidatas.put("errMsg", "token参数错误");
        }
        return apidatas;
    }

    /**
     * 校验userid
     *
     * @param encryptUserid
     * @return
     */
    public Map<String, Object> checkUserid(String encryptUserid) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String decUserid = Util.null2String(getDecryptStr(encryptUserid));
        String loginid = "";
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            loginid = Util.null2String(resourceComInfo.getLoginID(decUserid));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!"".equals(loginid)) {
            apidatas.put("code", "SUCCESS");
            apidatas.put("userid", decUserid);
        } else {
            apidatas.put("code", "HEAD_PARAM_ERROR");
            JSONObject dataJson = new JSONObject();
            dataJson.put("token", "人员ID不存在:" + decUserid);
            apidatas.put("data", dataJson);
            apidatas.put("errMsg", "token参数错误");
        }
        return apidatas;
    }

    /**
     * 校验requestid
     *
     * @param requestid
     * @return
     */
    public Map<String, Object> checkRequestid(String requestid) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        if (!"".equals(requestid)) {
            apidatas.put("code", "SUCCESS");
        } else {
            apidatas.put("code", "PARAM_ERROR");
            JSONObject dataJson = new JSONObject();
            dataJson.put("requestid", "唯一标识参数必填");
            apidatas.put("data", dataJson);
            apidatas.put("errMsg", "requestid参数为空");
        }
        return apidatas;
    }
    /**
     * 校验requestid
     *
     * @param mainData
     * @return
     */
    public Map<String, Object> checkMainData(String mainData) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        if (!"".equals(mainData)) {
            apidatas.put("code", "SUCCESS");
        } else {
            apidatas.put("code", "PARAM_ERROR");
            JSONObject dataJson = new JSONObject();
            dataJson.put("mainData", "主表字段必填");
            apidatas.put("data", dataJson);
            apidatas.put("errMsg", "mainData参数为空");
        }
        return apidatas;
    }

}
